package com.ruoyi.common.core.pay;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.ruoyi.common.core.utils.SpringUtils;
import com.alipay.api.AlipayConfig;

public class AlipayUtils {

	private static final com.ruoyi.common.core.pay.AlipayConfig payConfig = SpringUtils
			.getBean(com.ruoyi.common.core.pay.AlipayConfig.class);

	private static AlipayConfig alipayConfig = new AlipayConfig();

	public static void init() {
		// 设置应用ID
		alipayConfig.setAppId(payConfig.getAppId());
		// 设置应用私钥
		alipayConfig.setPrivateKey(payConfig.getPrivateKey());
		// 设置应用公钥证书路径
		alipayConfig.setAppCertPath(payConfig.getAppCertPath());
		// 设置支付宝公钥证书路径
		alipayConfig.setAlipayPublicCertPath(payConfig.getAlipayPublicCertPath());
		// 设置支付宝根证书路径
		alipayConfig.setRootCertPath(payConfig.getRootCertPath());
	}

	public static String webpagePay(String subject, String out_trade_no, Double total_amount) {
		init();
		AlipayClient alipayClient;
		try {
			alipayClient = new DefaultAlipayClient(alipayConfig);

			AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
			// 异步接收地址，仅支持http/https，公网可访问
			request.setNotifyUrl(payConfig.getCallbackUrl());
			// 同步跳转地址，仅支持http/https
			request.setReturnUrl("");
			/****** 必传参数 ******/
			JSONObject bizContent = new JSONObject();
			// 商户订单号，商家自定义，保持唯一性
			bizContent.put("out_trade_no", out_trade_no);
			// 支付金额，最小值0.01元
			if (payConfig.getIsTest())
				bizContent.put("total_amount", 0.01);
			else
				bizContent.put("total_amount", total_amount);

			// 订单标题，不可使用特殊符号
			bizContent.put("subject", subject);
			// 电脑网站支付场景固定传值FAST_INSTANT_TRADE_PAY
			bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");

			bizContent.put("qr_pay_mode", "2");

			/****** 可选参数 ******/
			// bizContent.put("time_expire", "2022-08-01 22:00:00");

			//// 商品明细信息，按需传入
			// JSONArray goodsDetail = new JSONArray();
			// JSONObject goods1 = new JSONObject();
			// goods1.put("goods_id", "goodsNo1");
			// goods1.put("goods_name", "子商品1");
			// goods1.put("quantity", 1);
			// goods1.put("price", 0.01);
			// goodsDetail.add(goods1);
			// bizContent.put("goods_detail", goodsDetail);

			//// 扩展信息，按需传入
			// JSONObject extendParams = new JSONObject();
			// extendParams.put("sys_service_provider_id", "2088511833207846");
			// bizContent.put("extend_params", extendParams);

			request.setBizContent(bizContent.toString());
			AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
			if (response.isSuccess()) {
				System.out.println("调用成功");
			} else {
				System.out.println("调用失败");
			}
			System.out.println(response.getBody());
			return response.getBody();
		} catch (AlipayApiException e) {
			e.printStackTrace();
		}
		return "";
	}

}
